﻿using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using SqlSugar.IOC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Wq.Extensions.Common;
using Wq.Model;
using XAct;

namespace Wq.Extensions.Setup
{
    public static class SqlSugarSetup
    {
        public static void AddSqlSugar(this IServiceCollection services)
        {
            var connections = AppSettings.app<SqlSugarConfig>("ConnectionStrings:DataBase");
            var entities = RuntimeHelper.GetProjectTypes()
               .Where(p => p.GetAttribute<TenantAttribute>()!= null && !p.IsInterface && !p.IsAbstract && !p.IsSealed)
              // .Where(p => typeof(EntitiesModel).IsAssignableFrom(p))
               .ToList();

            connections.ForEach(item => {
                // 注入SqlSugar
                services.AddSqlSugar(new IocConfig()
                {
                    ConfigId = item.ConfigId,
                    ConnectionString = item.ConnectionString,
                    DbType = item.DbType,
                    IsAutoCloseConnection = true,

                });

                // 日志打印
                services.ConfigurationSugar(db => {
                    db.GetConnection(item.ConfigId).Aop.OnLogExecuting = (sql, p) =>
                    {
                        Console.WriteLine(sql);
                    };
                });

                // 创建数据库
                SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    DbType = DbType.MySql,
                    ConnectionString = item.ConnectionString,
                    InitKeyType = InitKeyType.Attribute,
                    IsAutoCloseConnection = true,
                });
                db.DbMaintenance.CreateDatabase();

                foreach (var entitie in entities)
                {
                    object[] Attributes = entitie.GetCustomAttributes(typeof(TenantAttribute), false);
                    foreach (TenantAttribute attribute in Attributes)
                    {
                        if (attribute.configId.ToString() == item.ConfigId)
                            db.CodeFirst.InitTables(entitie);
                    }
                }
            });

        }
       
    }

    public class SqlSugarConfig
    {
        /// <summary>
        /// 多租户唯一标识
        /// </summary>
        public string ConfigId { get; set; }

        /// <summary>
        /// 连接字符串
        /// </summary>
        public string ConnectionString { get; set; }

        /// <summary>
        /// 连接类型
        /// </summary>
        public IocDbType DbType { get; set; }
    }
}
